﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Authorized
{
    /// <summary>
    /// 授权方法类
    /// </summary>
    public class SoftAuthorized
    {
        Tools.TxtLogHelper txt = new Tools.TxtLogHelper();
        #region 验证授权码
        /// <summary>
        ///  验证授权码
        /// </summary>
        /// <param name="filePath">配置文件路径</param>
        /// <returns></returns>
        public string CheckSysKeyCode(string filePath="")
        {
        
            Dictionary<string, object> dic = new Dictionary<string, object>();
            
            try
            {
                if (string.IsNullOrWhiteSpace(filePath))
                {
                    filePath = string.Format("{0}{1}.txt", AppDomain.CurrentDomain.BaseDirectory, Tools.ConfigReader.Reader["serFile"]);
                }             
                StreamReader sr = new StreamReader(filePath, Encoding.Default);
                string content;
                content = sr.ReadToEnd();
                sr.Dispose();
                if (string.IsNullOrWhiteSpace(content))
                {
                    dic.Add("result", false);
                    dic.Add("code", "100");
                    dic.Add("msg", "授权信息丢失，请先注册");
                   return JsonConvert.SerializeObject(dic);
                }
                var json = JsonConvert.DeserializeObject<JObject>(content);
                var info = JsonConvert.DeserializeObject<Dictionary<string, string>>(Tools.Encryption.DesDecrypt(json["keyCode"].ToString()));
                string macCode = GetLocalMac().Replace(":","");
                if (macCode.Trim().Equals(info["mac"].ToString().Trim()))
                {//验证运行设备是否是同一台设备
                    if (info["forever"].ToString().Equals("0"))
                    {
                        #region 非永久有效用户
                        string rDays = Tools.ConfigReader.Reader["Remind"];
                        if (string.IsNullOrWhiteSpace(rDays))
                        {
                            rDays = "7";
                        }
                        int days = int.Parse(info["left"].ToString());
                        if (days < 0)
                        {
                            dic.Add("result", false);
                            dic.Add("code", "120");
                            dic.Add("msg", "系统服务已到期");
                            return JsonConvert.SerializeObject(dic);
                        }
                        if (!info["editDate"].ToString().Trim().Equals(DateTime.Now.ToShortDateString().ToString()))
                        {
                            #region 如果最后更新日期与当日不是同一天，则进行编码更新
                            info["left"] = Convert.ToString(int.Parse(info["left"].ToString()) - 1);
                            info["editDate"] = DateTime.Now.ToShortDateString().ToString();
                            string keyCode = Tools.Encryption.DesEncrypt(JsonConvert.SerializeObject(info));
                            var d = new Dictionary<string, string>();
                            d["keyCode"] = keyCode;
                            d["companyName"] = info["companyName"];
                            d["companyCode"] = info["companyCode"];
                            d["startDate"] = info["startDate"];
                            d["endDate"] = info["endDate"];
                            this.SaveInfoToConfigFile(filePath, JsonConvert.SerializeObject(d));
                            //if (int.Parse(rDays) >= int.Parse(info["left"]))
                            //{
                            //    dic.Add("code", "210");
                            //    dic.Add("msg", string.Format("系统即将到期，请及时联系服务商，剩余天数：{0}", info["left"]));
                            //}
                            //else
                            //{
                            //    dic.Add("code", "200");
                            //    dic.Add("msg", "验证通过");
                            //}
                            //dic.Add("result", true);
                            //return JsonConvert.SerializeObject(dic);
                            #endregion
                        }
                        else
                        {
                            //dic.Add("result", true);
                            //dic.Add("code", "200");
                            //dic.Add("msg", "验证通过");
                            //return JsonConvert.SerializeObject(dic);
                        }

                        if (int.Parse(rDays) >= int.Parse(info["left"]))
                        {
                            dic.Add("code", "210");
                            dic.Add("msg", string.Format("系统即将到期，请及时联系服务商，剩余天数：{0}", info["left"]));
                        }
                        else
                        {
                            dic.Add("code", "200");
                            dic.Add("msg", "验证通过");
                        }
                        dic.Add("result", true);
                        return JsonConvert.SerializeObject(dic);

                        #endregion
                    }
                    else
                    {
                        #region 永久有效用户
                        dic.Add("result", true);
                        dic.Add("code", "200");
                        dic.Add("msg", "验证通过");
                        return JsonConvert.SerializeObject(dic);
                        #endregion
                    }
                }
                else
                {
                    dic.Add("result", false);
                    dic.Add("code", "110");
                    dic.Add("msg", "检测到您是非法用户");
                    return JsonConvert.SerializeObject(dic);
                }

            }
            catch (Exception ex)
            {
                dic.Add("result", false);
                dic.Add("code","2");
                dic.Add("msg", ex.Message);
            }
            return JsonConvert.SerializeObject(dic);

        }
        #endregion

        #region 获取网卡编码
        /// <summary>
        /// 获取网卡编码
        /// </summary>
        /// <returns></returns>
        private string GetLocalMac()
        {
            string mac = null;
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            return (mac);
        }
        #endregion

        #region 生成新的授权码
        /// <summary>
        /// 生成新的授权码
        /// </summary>
        /// <param name="keyCode">授权关键码</param>
        /// <param name="days">使用天数</param>
        /// <param name="isVip">是否永久有效</param>
        /// <param name="companyCode">编码</param>
        /// <param name="companyName">名称</param>
        /// <returns></returns>
        public string CreateNewKey(int keyCode, int days, bool isVip, string companyCode, string companyName,bool isMark=false,string path="")
        {
            int createCode = DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day+DateTime.Now.Hour;
            Dictionary<string, object> rdic = new Dictionary<string, object>();
            try
            {
                if (keyCode == createCode)
                {
                    string mac = GetLocalMac();
                    StringBuilder sb = new StringBuilder();
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("mac", mac.Trim().Replace(":", ""));//网卡地址
                    dic.Add("startDate", DateTime.Now.ToShortDateString().ToString());//开始日期
                    dic.Add("endDate", DateTime.Now.AddDays(days).ToShortDateString().ToString());//截止日期
                    dic.Add("editDate", DateTime.Now.AddDays(0).ToShortDateString().ToString());//编辑日期
                    dic.Add("companyCode", companyCode);//公司编码
                    dic.Add("companyName", companyName);//公司名称
                    dic.Add("left", days.ToString());
                    if (isVip)
                    {
                        dic.Add("forever", "1");
                    }
                    else
                    {
                        dic.Add("forever", "0");
                    }
                    string info = JsonConvert.SerializeObject(dic);
                    string newCode = Tools.Encryption.DesEncrypt(info);
                    if (!string.IsNullOrWhiteSpace(newCode))
                    {
                        rdic.Add("result", true);
                        rdic.Add("msg", newCode);
                        if (isMark)
                        {
                            dic["keyCode"] = newCode;
                            dic.Remove("forever");
                            dic.Remove("left");
                            dic.Remove("editDate");
                            SaveInfoToConfigFile(path,JsonConvert.SerializeObject(dic));
                        }
                    }
                    else
                    {
                        rdic.Add("result", false);
                        rdic.Add("msg", "生成异常");
                    }
                }
                else
                {
                    rdic.Add("result", false);
                    rdic.Add("msg", "授权码错误");
                }
            }
            catch (Exception ex)
            {
                rdic.Add("result", false);
                rdic.Add("msg", ex.Message);
            }
            return JsonConvert.SerializeObject(rdic);
        }
        #endregion

        #region 将授权信息保存至系统配置文件
        /// <summary>
        /// 将授权信息保存至系统配置文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="contents"></param>
        private void SaveInfoToConfigFile(string path,string contents)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(path))
                {
                    path = AppDomain.CurrentDomain.BaseDirectory;
                    path = string.Format("{0}{1}.txt", path, Tools.ConfigReader.Reader["serFile"]);
                }
                FileStream fs;
                StreamWriter sr;
                using (fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    using (sr = new StreamWriter(fs))
                    {
                        sr.Write(contents);//开始写入值
                    }
                }
                sr.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {
        
            }
          
           
           
        }
        #endregion

      

        public bool InitAuthorized()
        {
            try
            {
                var path = AppDomain.CurrentDomain.BaseDirectory;
                path = string.Format("{0}/sysKey",path);
                if (!System.IO.File.Exists(path))
                {
                    FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件 
                    fs1.Close();
                }
            }
            catch (Exception ex)
            { 
            
            }
            return false;
        }
    }
}
